//
//  RequestManager.swift
//  sui04mac
//
//  Created by 杨剑 on 2023/11/28.
//

import Foundation
import SwiftUI
import Alamofire

class RequestManager {
    static var share = RequestManager()
    
//    AF.request("http://rs.easemob.com/easemob/server.json?app_key=\(appkey)",method: .get)
//        .responseDecodable(of: DecodableType.self) { response in

    
    
    
    func generateURL(appModel : AppModel , rest : RestModel,urlArgs : [String : String]) -> String{
        var urlText = ""
        urlText = "\(rest.urlTemplate.original_urlString)"
            .replacingOccurrences(of: "{host}", with: appModel.cluster.base_url)
            .replacingOccurrences(of: "{org}", with: appModel.org_name)
            .replacingOccurrences(of: "{app}", with: appModel.app_name)
        
        if urlText.count > 0 {
            for key in urlArgs.keys {
                if let value = urlArgs[key] {
                    if value.count > 0 {
                        urlText = urlText
                            .replacingOccurrences(of: key, with: value)
                    }
                }
            }
        }
        return urlText
    }
    
    
    func generateEMToken(appModel : AppModel) -> (String,String) {
        return ("Authorization","Bearer \(appModel.access_token)")
    }
    
//    func asDictionary() throws -> [String:Any] {
//        let data = try JSONEncoder().encode(Encodable.)
//        guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any] else {
//            throw NSError()
//        }
//        return dictionary
//    }

    
    func uploadFile(appModel : AppModel,rest : RestModel,urlArgs : [String : String],filePath : String,fileData : Data,curlCompletion:@escaping (String) -> Void,completion:@escaping (String, Int) -> Void){
        //拼装url
        let url = generateURL(appModel: appModel, rest: rest, urlArgs: urlArgs)
        //拼装header
        var headers = HTTPHeaders()
        if rest.urlTemplate.needAuthorizationVerify {
            let (tokenKey,tokenValue) = generateEMToken(appModel: appModel)
            headers.add(name: tokenKey, value: tokenValue)
        }
        print(headers)
//        print(body)
        print(url)

//        _request(method: rest.urlTemplate.method, url: url, headers: headers,contentType: rest.urlTemplate.contentType , body: [String : Any](),curlCompletion: curlCompletion,completion: completion)

        _upload(method: rest.urlTemplate.method, url: url, headers: headers, contentType: rest.urlTemplate.contentType, filePath: filePath,fileData: fileData, curlCompletion: curlCompletion, completion: completion)
    }
    
    
    func request(appModel : AppModel,rest : RestModel,urlArgs : [String : String],body : [String:Any] = [:],curlCompletion:@escaping (String) -> Void,completion:@escaping (String, Int) -> Void){
        //拼装url
        let url = generateURL(appModel: appModel, rest: rest, urlArgs: urlArgs)
        
        //拼装header
        var headers = HTTPHeaders()
        if rest.urlTemplate.needAuthorizationVerify {
            let (tokenKey,tokenValue) = generateEMToken(appModel: appModel)
            headers.add(name: tokenKey, value: tokenValue)
        }
//        if !body.isEmpty {
//            if rest.urlTemplate.contentType == .application__json {
//                headers["Content-Type"] = "application/json"
////                headers["Accept"] = "application/json"
//            }else if rest.urlTemplate.contentType == .application__x_www_form_urlencoded {
//                headers["content-type"] = "application/x-www-form..."
//            }
//        }
//        headers["content-type"] = "application/json"

        print(headers)
        print(body)
//        print(rest.urlTemplate.method)
        print(url)

        _request(method: rest.urlTemplate.method, url: url, headers: headers,contentType: rest.urlTemplate.contentType , body: body,curlCompletion: curlCompletion,completion: completion)
    }
    
    func _request(method:HTTPMethod, url : String ,headers : HTTPHeaders,contentType : RequestDataType, body : [String : Any] = [:],curlCompletion:@escaping (String) -> Void, completion:@escaping (String, Int) -> Void){
        var encoding : ParameterEncoding = URLEncoding.default
        if body.count > 0 {
            if contentType == .application__json {
                encoding = JSONEncoding.default
            }
            if contentType == .application__x_www_form_urlencoded {
                encoding = URLEncoding.default
            }
        }else {
//            if contentType == .multipart__form_data {
//                encoding = URLEncoding.
//            }
        }
        
        AF.request(url,method: method,parameters: body ,encoding: encoding,headers: headers)
            .cURLDescription(calling: { curl in
                print(curl)
                curlCompletion(curl)
            })
            .responseString(encoding: String.Encoding.utf8) { response in
                let statusCode = response.response?.statusCode ?? 0
                var result : String = ""
                if let text = response.value {
                    do {
                        let jsonObject = try JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: [.allowFragments]) as? [String : Any]
                        let jsonData = try JSONSerialization.data(withJSONObject: jsonObject!, options: [.prettyPrinted,.withoutEscapingSlashes])
                        result = String(data: jsonData, encoding: .utf8) ?? text
//                        if let jsonString = (String(data: jsonData, encoding: .utf8) ?? text) as String {
//                            result = "\(jsonObject)"
//                        }else{
//                            result = text
//                        }
//                        result = "\(jsonObject)"
//                        result = "\(jsonObject)"
                    } catch {
                        result = text
                    }
                }else if let error = response.error {
                    result = "APP请求错误(这里是指本应用请求错误,并未到达服务端)\n\(error)"
                }
                
                print(statusCode)
                print(result)
                completion(result,statusCode)
            }
    }
        
    func _upload(method:HTTPMethod, url : String,headers : HTTPHeaders,contentType : RequestDataType,filePath : String,fileData : Data,curlCompletion:@escaping (String) -> Void, completion:@escaping (String, Int) -> Void) {
        
        
//        guard let data = filePathToData(filePath: filePath) else {
//            completion("错误:文件不存在",1000);
//            return;
//        }
        
        
        
        
        
        let fileURL = URL(fileURLWithPath: filePath) //{
        
        
        let data = try? Data(contentsOf: fileURL)
        print(fileURL) // 输出文件URL
//        } else {
//            print("无法创建文件URL")
//        }

        
//        let data =
//        AF.upload
        let data1 = getFileData(filePath: filePath)
        
        
        
        
        AF.upload(multipartFormData: { multipartFormData in
            // 附加文件到表单数据
            multipartFormData.append(fileData, withName: "file", fileName: "testFile", mimeType:nil)

//            if let fileData = try? Data(contentsOf: fileURL) {
//            }

            // 附加其他表单字段（如果需要的话）
//            multipartFormData.append("your-field-value".data(using: .utf8)!, withName: "your-field-name")
        }, to: url,method: method,headers: headers)
            .cURLDescription(calling: { curl in
                print(curl)
                curlCompletion(curl)
            })

            .responseString(encoding: String.Encoding.utf8) { response in
                let statusCode = response.response?.statusCode ?? 0
                var result : String = ""
                if let text = response.value {
                    do {
                        let jsonObject = try JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: [.allowFragments]) as? [String : Any]
                        let jsonData = try JSONSerialization.data(withJSONObject: jsonObject!, options: [.prettyPrinted,.withoutEscapingSlashes])
                        result = String(data: jsonData, encoding: .utf8) ?? text
//                        if let jsonString = (String(data: jsonData, encoding: .utf8) ?? text) as String {
//                            result = "\(jsonObject)"
//                        }else{
//                            result = text
//                        }
//                        result = "\(jsonObject)"
//                        result = "\(jsonObject)"
                    } catch {
                        result = text
                    }
                }else if let error = response.error {
                    result = "APP请求错误(这里是指本应用请求错误,并未到达服务端)\n\(error)"
                }
                print(statusCode)
                print(result)
                completion(result,statusCode)
            }
        
    }
    func getFileData(filePath: String) -> Data? {
        let fileManager = FileManager.default
        return fileManager.contents(atPath: filePath)

//        do {
//            let url = URL(fileURLWithPath: filePath)
//            
//            // 使用FileManager读取文件内容
//        } catch {
//            // 处理可能出现的错误，例如文件不存在
//            print("无法读取文件：\(error.localizedDescription)")
//            return nil
//        }
    }

    
}


//extension Dictionary : ParameterEncoding {
//    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
//        
//    }
//}
/*
 curl -v \
     -X PUT \
     -H "Accept-Language: zh-Hans-CN;q=1.0, en;q=0.9, fr;q=0.8, de;q=0.7, zh-Hans;q=0.6, zh-Hant;q=0.5" \
     -H "User-Agent: sui04mac/1.0 (com.jj.sui04mac; build:1; macOS 14.1.1) Alamofire/5.8.0" \
     -H "Accept-Encoding: br;q=1.0, gzip;q=0.9, deflate;q=0.8" \
     -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" \
     -H "Authorization: Bearer YWMtHXl20pNMEe6LZXNmRHIKKFOaBn8hITJOq1PUZikodyC5Sq5QvqUR54iL68wI_skmAgMAAAGMOTD_ZDeeSACTPsH2RYKZhbfvyCzd0j7LtfDOemymhg_q0ThdSUqJ9w" \
     -d "avatarurl=http%3A//%E5%9B%BE%E7%89%87%E9%93%BE%E6%8E%A5.jpg&ext=%E9%9C%80%E8%A6%81%E6%B3%A8%E6%84%8F%E7%9A%84%E6%98%AF%2C%E8%BF%99%E9%87%8C%E7%9A%84%E5%AD%97%E6%AE%B5%E9%83%BD%E6%98%AF%E5%8F%AF%E9%80%89%E5%AD%97%E6%AE%B5%2C%E9%9C%80%E8%A6%81%E8%AE%BE%E7%BD%AE%E5%93%AA%E4%B8%80%E4%B8%AA%E5%AD%97%E6%AE%B5%E5%88%99%E6%B7%BB%E5%8A%A0%E5%93%AA%E4%B8%80%E4%B8%AA%E5%AD%97%E6%AE%B5%2C%E5%A6%82%E6%9E%9C%E4%B8%8D%E9%9C%80%E8%A6%81%E8%AE%BE%E7%BD%AE%2C%E4%B9%9F%E4%B8%8D%E8%83%BD%E7%BB%99%E5%AE%9A%E7%A9%BA%E5%AD%97%E6%AE%B5%2C%E5%9B%A0%E4%B8%BA%E8%BF%99%E7%9B%B8%E5%BD%93%E4%BA%8E%E8%AE%BE%E5%AE%9A%E4%BA%86%E4%B8%80%E4%B8%AA%E5%AD%97%E6%AE%B5%E4%B8%BA%E7%A9%BA%E5%80%BC&nickname=%E6%98%B5%E7%A7%B0" \
     "https://a1.easemob.com/1168171101115760/dabaojian/metadata/user/%7Busername%7D"
 
 
 */
